package com.todo.auth.conf;

import com.todo.common.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author azhebuxing
 * @date 2025/2/20 17:05
 * @description
 */
@Slf4j
@Configuration
public class OAuth2FeignConfig implements RequestInterceptor {
    // 在每一个请求里面，都会被调用
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 将 request 的上下文环境获取 token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.info("没有请求的上下文，故无法进行token的传递");
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);   // 获取请求上下文的头里面的AUTHORIZATION
        if (!StringUtils.isEmpty(header)) {
            // token 传递
            requestTemplate.header(HttpHeaders.AUTHORIZATION, header);
            log.info("本次token传递成功，token值为{}", header);
        }
    }
}
